<script lang="tsx">
import { defineComponent, Transition, watch, ref, onMounted, onUnmounted, type PropType } from 'vue';
import { ElTag, ElButton } from 'element-plus';
import { Trash2, Search } from '@vben/icons';
import { useRecentSearch } from './hooks/useRecentSearch';
import { useHotSearch } from './hooks/useHotSearch';

export default defineComponent({
  name: 'SearchSuggestion',
  props: {
    // 搜索关键词
    keyword: {
      type: String,
      default: ''
    },
    // 是否显示弹出框
    visible: {
      type: Boolean,
      default: false
    },
    // 搜索容器的引用，用于排除点击外部检测
    searchContainer: {
      type: Object as PropType<HTMLElement>,
      default: null
    }
  },
  emits: ['update:visible', 'search', 'select'],
  setup(props, { emit }) {
    const suggestionRef = ref<HTMLElement>();
    
    const {
      recentSearchList,
      hasRecentSearch,
      removeRecentSearch,
      clearRecentSearch,
      loadRecentSearch
    } = useRecentSearch();

    const { hotSearchList, loading: hotSearchLoading } = useHotSearch();

    // 监听弹出框显示状态，重新加载最近搜索数据
    watch(() => props.visible, (newVisible) => {
      if (newVisible) {
        loadRecentSearch();
      }
    });

    // 点击外部关闭弹出框
    const handleClickOutside = (event: MouseEvent) => {
      if (!props.visible) return;
      
      const target = event.target as Node;
      const isClickInsideSuggestion = suggestionRef.value?.contains(target);
      const isClickInsideSearchContainer = props.searchContainer?.contains(target);
      
      if (!isClickInsideSuggestion && !isClickInsideSearchContainer) {
        emit('update:visible', false);
      }
    };

    onMounted(() => {
      document.addEventListener('click', handleClickOutside);
    });

    onUnmounted(() => {
      document.removeEventListener('click', handleClickOutside);
    });

    // 处理搜索项点击
    const handleSearchItemClick = (keyword: string) => {
      emit('select', keyword);
      emit('update:visible', false);
    };

    // 处理删除最近搜索项
    const handleRemoveRecentSearch = (keyword: string, event: Event) => {
      event.stopPropagation();
      removeRecentSearch(keyword);
    };

    // 处理清空最近搜索
    const handleClearRecentSearch = () => {
      clearRecentSearch();
    };

    return () => (
      <Transition
        name="search-suggestion"
        enterActiveClass="transition-all duration-200 ease-out"
        enterFromClass="opacity-0 transform scale-95"
        enterToClass="opacity-100 transform scale-100"
        leaveActiveClass="transition-all duration-150 ease-in"
        leaveFromClass="opacity-100 transform scale-100"
        leaveToClass="opacity-0 transform scale-95"
      >
        {props.visible && (
          <div 
            ref={suggestionRef}
            class="absolute top-full left-0 right-0 mt-2 bg-white rounded-xl shadow-lg border border-gray-200 z-50 search-suggestion-panel"
          >
            <div class="p-4">
              {/* 最近搜索 */}
              {hasRecentSearch.value && (
                <div class="mb-4">
                  <div class="flex items-center justify-between mb-3">
                    <span class="text-sm font-medium text-gray-700">最近搜索</span>
                    <ElButton
                      type="text"
                      size="small"
                      class="text-gray-400 hover:text-gray-600"
                      onClick={handleClearRecentSearch}
                    >
                      <Trash2 class="w-4 h-4" />
                    </ElButton>
                  </div>
                  <div class="flex flex-wrap gap-2">
                    {recentSearchList.value.map((item) => (
                      <ElTag
                        key={item}
                        class="cursor-pointer hover:bg-blue-50 hover:border-blue-200 transition-colors"
                        closable
                        onClose={(event: Event) => handleRemoveRecentSearch(item, event)}
                        onClick={() => handleSearchItemClick(item)}
                      >
                        {item}
                      </ElTag>
                    ))}
                  </div>
                </div>
              )}

              {/* 热门搜索 */}
              {hotSearchList.value.length > 0 && (
                <div class={hasRecentSearch.value ? 'border-t pt-4' : ''}>
                  <div class="flex items-center justify-between mb-3">
                    <span class="text-sm font-medium text-gray-700">热门搜索</span>
                  </div>
                  <div class="flex flex-wrap gap-2">
                    {hotSearchList.value.map((item, index) => (
                      <ElTag
                        key={`hot-${index}`}
                        type="info"
                        class="cursor-pointer hover:bg-orange-50 hover:border-orange-200 transition-colors"
                        onClick={() => handleSearchItemClick(item)}
                      >
                        {item}
                      </ElTag>
                    ))}
                  </div>
                </div>
              )}

              {/* 暂无搜索记录时的提示 */}
              {!hasRecentSearch.value && hotSearchList.value.length === 0 && !hotSearchLoading.value && (
                <div class="text-center py-8 text-gray-400">
                  <Search class="w-8 h-8 mx-auto mb-2 opacity-50" />
                  <p class="text-sm">暂无搜索记录</p>
                </div>
              )}

              {/* 加载状态 */}
              {hotSearchLoading.value && (
                <div class="text-center py-4 text-gray-400">
                  <p class="text-sm">加载中...</p>
                </div>
              )}
            </div>
          </div>
        )}
      </Transition>
    );
  }
});
</script>

<style lang="less" scoped>
.search-suggestion-panel {
  max-height: 400px;
  overflow-y: auto;
}

:deep(.el-tag) {
  border-radius: 6px;
  padding: 4px 8px;
  font-size: 12px;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .el-tag__close {
    margin-left: 4px;
    font-size: 10px;
  }
}

:deep(.el-button--text) {
  padding: 4px;
  min-height: auto;
}

.search-suggestion-enter-active,
.search-suggestion-leave-active {
  transition: all 0.2s ease;
}

.search-suggestion-enter-from,
.search-suggestion-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}
</style>
